// Copyright  2012 Petr TALLA. [petr.talla@gmail.com]
// This file is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This file is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY;  without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Lesser General Public License for more details.
// [http://www.gnu.org/copyleft/lesser.html]
//=============================================================================

package tc.crase.cmds;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Box;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.filechooser.FileNameExtensionFilter;

import tc.common.registry.Ref;
import tc.common.registry.RegistrySys;
import tc.common.registry.Rview;
import tc.common.utility.GrView;
import tc.common.utility.TcDisplayTransf;

import tc.crase.db.Xobject;
import tc.crase.save.XdbLoad;
import tc.crase.save.XdbSave;
import tc.crase.sys.XdbEx;
import tc.crase.sys.XdbRoot;
import tc.crase.sys.XobjectEx;

public class CmdLoadSave extends CmdEx  implements ActionListener {
	
	static boolean loaded = false;
	JLabel fileLabel;
	JLabel uptodateLabel;
	JLabel lastOperationLabel;
	static UptodateChecker uptodate = null;
	
	JList list;
	JTextField renameText;
	
	void setLastOpperation(String status, boolean error) {
		if (status.isEmpty()) {
			lastOperationLabel.setText("");
			return;
		}
		
		String text = new String("<html>Last opperation: ");
		if (error) text = text.concat("<span color='red'><b>");
		text = text.concat(status);
		if (error) text = text.concat("</b></span>");
		text = text.concat("<html>");
		
		lastOperationLabel.setText(text);
	}
	
	String fileShort(String fileName, int size) {
		if (fileName.length() < size) return fileName;
		int form = fileName.length() - size;
		if (form < 0 ) form = 0;
		return "..." + fileName.substring(form);
	}
	
	public CmdLoadSave() {
		if (uptodate == null) uptodate = new UptodateChecker();
	}
	
	private void update() {
		String fileName = XdbRoot.xdbsys.current.fileName;
		if (fileName.isEmpty()) fileName = "Nothing loaded";
		fileLabel.setText("<html><p><b>" + fileShort(fileName, 16) + "</b></p></html>");
		
		if (uptodate.changed) {
			uptodateLabel.setText("<html><p color='red'><b>NOT saved.</b></color></html>");
		}
		else {
			uptodateLabel.setText("Up to date.");
		}
		
		DefaultListModel listModel = new DefaultListModel();
		
		/*for (Doc doc : XdbRoot.xdbsys.current.getDocs()) {
			listModel.addElement(doc.name);
		}*/	
		
		for (XdbEx xdb : XdbRoot.xdbsys.dbs) {
			if (xdb.fileName.isEmpty()) { 
				listModel.addElement("NONAME");
			}
			else {
				/*File file = new File(xdb.fileName);
				int form = xdb.fileName.length() - 20;
				if (form < 0 ) form = 0;
				listModel.addElement("..." + xdb.fileName.substring(form));*/
				
				listModel.addElement(fileShort(xdb.fileName, 20));
			}
		}
		
		list.setModel(listModel);
	}
	
	public void initializeDialog() {
		super.initializeDialog();
		setLabel("Load/Save");
		setHint("Click button to open or save a file.");
		
		fileLabel = new JLabel("");
		uptodateLabel = new JLabel("");
		lastOperationLabel = new JLabel("");
				
		JButton fileButtonLoad = new JButton("Load");
		fileButtonLoad.addActionListener(this);
		fileButtonLoad.setActionCommand("load");
		fileButtonLoad.setPreferredSize(new Dimension(SIDEBAR_WIDTH,24));
		fileButtonLoad.setMaximumSize(new Dimension(SIDEBAR_WIDTH,24));
		
		JButton fileButtonLoadMeta = new JButton("Load Metadata");
		fileButtonLoadMeta.addActionListener(this);
		fileButtonLoadMeta.setActionCommand("loadMeta");
		fileButtonLoadMeta.setPreferredSize(new Dimension(SIDEBAR_WIDTH,24));
		fileButtonLoadMeta.setMaximumSize(new Dimension(SIDEBAR_WIDTH,24));
		
		JButton fileButtonSave = new JButton("Save");
		fileButtonSave.addActionListener(this);
		fileButtonSave.setActionCommand("save");
		fileButtonSave.setPreferredSize(new Dimension(SIDEBAR_WIDTH,24));
		fileButtonSave.setMaximumSize(new Dimension(SIDEBAR_WIDTH,24));
		
		list = new JList();
		list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		list.setLayoutOrientation(JList.VERTICAL);
		list.setMinimumSize(new Dimension(SIDEBAR_WIDTH,150));
		list.setPreferredSize(new Dimension(SIDEBAR_WIDTH,150));
		list.setMaximumSize(new Dimension(SIDEBAR_WIDTH,220));
		//JScrollPane listScroller = new JScrollPane(list);
		//updateList();
		
		JButton createButton = new JButton("Make Active");
		createButton.addActionListener(this);
		createButton.setActionCommand("makeActive");
		createButton.setPreferredSize(new Dimension(SIDEBAR_WIDTH,24));
		createButton.setMaximumSize(new Dimension(SIDEBAR_WIDTH,24));

		dialog.add(uptodateLabel);
		dialog.add(Box.createRigidArea(new Dimension(0,10)));
		dialog.add(fileButtonLoad);
		dialog.add(Box.createRigidArea(new Dimension(0,3)));
		dialog.add(fileButtonSave);
		dialog.add(Box.createRigidArea(new Dimension(0,10)));
		dialog.add(fileLabel);
		dialog.add(Box.createRigidArea(new Dimension(0,5)));
		dialog.add(list);
		dialog.add(Box.createRigidArea(new Dimension(0,10)));
		dialog.add(createButton);
		dialog.add(Box.createRigidArea(new Dimension(0,50)));
		dialog.add(fileButtonLoadMeta);


		finalizeDialog();
		
		update();
	}
	
	public void enterPoint(Point pt, GrView view) {
	}
	public void enterReset(GrView view) {
	}
	public void enterMove(Point pt, GrView view)  {
	}
	
	private void draw(Graphics g, TcDisplayTransf transf, Color background)
	{
	}
	
	public void actionPerformed(ActionEvent e) {
		if ("save".equals( e.getActionCommand() )) {
			for (XdbEx db : XdbRoot.xdbsys.dbs ) {
				if ( save(db) == false ) break;
			}
		}	
		else if ( "load".equals( e.getActionCommand()) || "loadMeta".equals( e.getActionCommand()) ) {
			load("loadMeta".equals( e.getActionCommand()));
		}
		else if ( "makeActive".equals( e.getActionCommand() ) ) {
			XdbEx xdbSel = XdbRoot.xdbsys.dbs.get(list.getSelectedIndex());
			if (XdbRoot.xdbsys.current == xdbSel) return;
			
			RegistrySys.registry.lock(); {
				for (Xobject xobj : XdbRoot.xdbsys.current) {
					XobjectEx xobjEx = (XobjectEx)xobj;
					xobjEx.objex.objChanged();
				}
				XdbRoot.xdbsys.current = xdbSel;
				for (Xobject xobj : XdbRoot.xdbsys.current) {
					XobjectEx xobjEx = (XobjectEx)xobj;
					xobjEx.objex.objChanged();
				}
			} RegistrySys.registry.unlock();
		}
		
		update();
	}
	
	public boolean save(XdbEx xdb) {
		if ( xdb.fileName.isEmpty() ) {
			JFileChooser chooser = new JFileChooser();
			chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
			FileNameExtensionFilter filter = new FileNameExtensionFilter("CRASE file", "crase");
		    chooser.setFileFilter(filter);
			int returnVal = chooser.showSaveDialog(null);
			if(returnVal != JFileChooser.APPROVE_OPTION) 
			{	setLastOpperation("No file selected.", false);
				return false;
			}
			xdb.fileName = chooser.getSelectedFile().toString();
		}
		
		if ( xdb.fileName.isEmpty() ) {
			setLastOpperation("File name not entered.", true);
			return false;
		}
		
		XdbSave saver = new XdbSave(xdb);
		boolean result = saver.save();
		if (result) {
			uptodate.changed = false;
		}
		else {
			setLastOpperation(saver.status, true);
			return false;
		}
		
		return true;
	}
	
	public void load(boolean loadMeta) {
		 
		
		/*if (loadMeta == false) {
			if (currentDb.fileName.isEmpty() == false) {
				setLastOpperation("File already loaded. Nothing happened.", true);
				return;
			}
		}*/
		
		JFileChooser chooser = new JFileChooser();
		FileNameExtensionFilter filter = new FileNameExtensionFilter("CRASE file", "crase");
		chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		if (loadMeta) filter = new FileNameExtensionFilter("CRASE metadata", "crase_");
	    chooser.setFileFilter(filter);
		int returnVal = chooser.showOpenDialog(null);
		if(returnVal != JFileChooser.APPROVE_OPTION) 
		{	setLastOpperation("No file selected.", false);
			return;
		}
		
		//if (currentDb.fileName.isEmpty() == false) 
		
		String fileName = chooser.getSelectedFile().toString();
		
		RegistrySys.registry.lock(); {
			if (loadMeta) {
				XdbLoad loader = new XdbLoad(XdbRoot.xdbsys.current);
				boolean result = loader.load(chooser.getSelectedFile(), true);
				
				if (result) {
					setLastOpperation("Loaded sucesfully.", false);
				}
				else {
					setLastOpperation(loader.status, true);
				}
			}
			else {
				for (XdbEx db : XdbRoot.xdbsys.dbs ) {
					if ( fileName.equals(db.fileName) == false) continue;
					setLastOpperation("File already loaded.", false);
					RegistrySys.registry.unlock();
					return;
				}
				
				XdbEx currentDb = XdbRoot.xdbsys.searchDb(fileName);
				XdbRoot.xdbsys.current = currentDb;
			}
		} RegistrySys.registry.unlock();
		
		uptodate.changed = loadMeta;
	}
	
	public class UptodateChecker implements Rview {
		public UptodateChecker() {
			RegistrySys.registry.views.add(this);
		}
		
		public boolean changed = false;
		
		public void checkPresence() {
			if ( RegistrySys.registry.changed.size() == 0 ) return;
			changed = true;
		};
		
		public boolean getDirty(){return false; };
		public void setDirty(boolean value){};
		public void updateRview(){};
		public void onRefChanged(Ref ref){};
	}
}
